﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JSON;
using System.Web;
using Facebook_Graph_Toolkit.FacebookObjects;

namespace Facebook_Graph_Toolkit {
    /// <summary>
    /// Inherit this class in a page that will be displayed in an Page tab
    /// </summary>
    public class TabPage : System.Web.UI.Page{
        private JsonObject data;
        private GraphApi.Api _Api=null;
        /// <summary>
        ///Stores the current Access Token and provides methods to make Api calls
        /// </summary>
        public GraphApi.Api Api {
            get {
                return _Api;
            }
        }

        #region Login Settings
        /// <summary>
        /// Whether the user is required to authorize the application to view this page
        /// </summary>
        public bool RequireLogin = false;
        /// <summary>
        /// The user will be prompted to grant these Extended Permissions at authorization
        /// </summary>
        public string ExtendedPermissions = "";
        /// <summary>
        /// Whether or not to check if the user has already granted the extended permissions. If not, the library will redirect the user to do so.
        /// </summary>
        public bool CheckExtendedPermissions = false;
        /// <summary>
        /// The ID of the Facebook Page which contains this TabPage
        /// </summary>
        public string FacebookPageID = null;
        #endregion

        /// <summary>
        /// Manages Facebook Application configuration of this page
        /// </summary>
        public FacebookAppConfig FacebookAppConfig = new FacebookAppConfig();

        #region ApiData
        /// <summary>
        /// Basic data about the current view of this page at a Page tab
        /// </summary>
        public BasicPageData PageData { get { return new BasicPageData((JsonObject)data["page"]); } }
        /// <summary>
        /// Basic data about the user who is browsing this Iframe Application
        /// </summary>
        public BasicUserData UserData { get { return new BasicUserData((JsonObject)data["user"]); } }
        #endregion

        /// <summary>
        /// OnLoad method
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e) {
            if (!IsPostBack) {
                string SignedRequest = HttpContext.Current.Request["signed_request"];
                if (SignedRequest == null) {
                    throw new FacebookException("Cannot find Facebook POST data as expected. Make sure you're viewing this page in an Iframe Application Tab of a Facebook Page.");
                }

                FacebookAppConfig.GetDefaultConfig();
                data = Helpers.Common.ParseSignedRequest(SignedRequest, FacebookAppConfig.FacebookAppSecret);

                if (data["oauth_token"] != null) {
                    if (data["expires"] != null) _Api = new GraphApi.Api((string)data["oauth_token"], Helpers.Common.UnixTimestampToDateTime((int)data["expires"]));
                    else _Api = new GraphApi.Api((string)data["oauth_token"]);
                }
                ViewState["GraphApi"] = _Api;
            } else {
                _Api = (GraphApi.Api)ViewState["GraphApi"];
            }

            bool RedirectForExtendedPermission = false;
            if (_Api != null && CheckExtendedPermissions && !string.IsNullOrEmpty(ExtendedPermissions.Trim())) {
                JsonArray JA = Helpers.ApiCaller.FqlFresh(string.Format("SELECT {0} FROM permissions WHERE uid = me()", ExtendedPermissions), _Api.AccessToken);
                JsonObject JO = (JsonObject)JA[0];
                foreach(KeyValuePair<string,object> KVP in JO) {
                    if ((int)KVP.Value == 0) {
                        RedirectForExtendedPermission = true;
                        break;
                    }
                }
            }

            if ((_Api == null && RequireLogin) || RedirectForExtendedPermission) {
                RedirectToFacebookAuthorization();
            }

            base.OnLoad(e);
        }
        /// <summary>
        /// Redirect the user to authorize the Application
        /// </summary>
        protected void RedirectToFacebookAuthorization() {
            if (string.IsNullOrEmpty(FacebookPageID)) {
                throw new ArgumentNullException("FacebookPageID", "Must not be null or empty.");
            }
            GraphApi.Page P = new GraphApi.Page(FacebookPageID);
            string RedirectUrl = P.NavigateUrl + "?sk=app_" + FacebookAppConfig.FacebookAppID;
            string AuthorizeUrl = String.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", FacebookAppConfig.FacebookAppID, RedirectUrl, ExtendedPermissions);
            Helpers.IframeHelper.IframeRedirect(AuthorizeUrl, false, true);
        }
    }
}
